<template>
  <div style="position:relative; width:auto;" v-clickoutside="handlerClose" >
    <div>
      <el-input type="text" v-model="inputValue" @focus="showPanel"></el-input>
    </div>
    <div
      style="position:absolute;background:#FFF;z-index:99999;overflow-y:auto;overflow-x:auto;width: 300px;height: 200px" v-show="show" class="el-select-dropdown"
      :style="{width: autoWidth + 'px',height: autoHeight + 'px'}">
        <el-tree :props="treeProps" lazy  ref="tree" :load="loadChildNode" @node-click="handleNodeClick" :highlight-current="true" :check-on-click-node = "true" :expand-on-click-node="false" ></el-tree>
    </div>
  </div>
</template>
<script>
  import co from '../../utils/clickoutside'
  export default {
    directives: {clickoutside: co.clickoutside},
    data () {
      return{
        autoWidth:'',
        autoHeight:'',
        treeProps :{label: 'name', id: 'id', children: 'children', isLeaf: 'leaf'},
        show:false,
        inputValue:''
      }
    },
    methods: {
      // 点击当前选择的区划树
      handleNodeClick (target) {
        this.inputValue = target.name
        this.$emit('treeSelected', target)
        this.$emit('showResult', target.id)
        this.handlerClose()
      },
      // input框获得焦点时，弹出下方div框
      showPanel () {
        this.show = true
      },
      // 页面任意位置点击时，关闭下方div框
      handlerClose () {
        this.show = false
      },
      // 加载区划树
      loadChildNode (node, resolve) {
        let orgArray = []
        this.axios.request({
          method: "get",
          url: "./ope/kdi/yard/search/findAllTree",
          params: {}
        }).then(response => {
          response.data.forEach(element => {
            if (node.level === 0) { // 顶层
              orgArray = [{
                id: element.uuid,
                name: element.name,
                children: [],
              }]
              return resolve(orgArray)
            } else if (node.level === 1) {// 第二层
              this.axios.request({
                method: "get",
                url: "./ope/kdi/yard/search/findByPat/"+node.data.id,
                params: {}
              }).then(response =>{
                response.data.forEach(element => {
                  orgArray.push({id: element.uuid, name: element.name, leaf: false, children: []})
                })
                return resolve(orgArray)
              })
            } else if (node.level === 2) { //第三层
              this.axios.request({
                method: "get",
                url: "./ope/kdi/yard/search/findByPat/"+node.data.id,
                params: {}
              }).then(response =>{
                response.data.forEach(element => {
                  orgArray.push({id: element.uuid, name: element.name, leaf: true})
                })
                return resolve(orgArray)
              })
            }
          })
        })
      },
    }
  }
</script>
